import {throttle} from "../../utils/utils";

Component({
  // 多插槽时要在组件js增加option配置项
  options: {
    multipleSlots: true
  },
  properties: {
    tabs: {
      type: Array,
      value: []
    },
    active: {
      type: Number,
      value: 0
    }
  },
  observers: {
    active(active) {
      this.setData({
        currentTabIndex: active
      })
    }
  },
  data: {
    currentTabIndex: 0
  },
  methods: {
    handleTabChange: throttle(function (event) {
      const index = event.currentTarget.dataset.index
      if (index === this.data.currentTabIndex) {
        return
      }
      this.setData({
        currentTabIndex: index
      })
      this.triggerEvent('change', {index})
    }),
    handleTouchMove(event) {
      const direction = event.direction
      const currentTabIndex = this.data.currentTabIndex
      const targetTabIndex = currentTabIndex + direction
      if (targetTabIndex < 0 || targetTabIndex > this.data.tabs.length - 1) {
        return
      }
      const custonEvent = {
        currentTarget: {
          dataset: {
            index: targetTabIndex
          }
        }
      }
      this.handleTabChange(custonEvent)
    },
  }
});
